//app.js
import handle from 'utils/handle.js';
import requestL from 'utils/requestL.js';
import data from 'utils/data.js';
App({
  onLaunch: function() {
    // 展示本地存储能力
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
    let that = this; //定义全局
    // 登录
    wx.login({
      success: function(res) {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        wx.request({
          url: data.lyf_host_api_url + '/public/index.php/energy/api.User/getOpenId', //获取OpenId
          data: {code: res.code},
          header: {
            'content-type': 'application/json' //默认值
          },
          success: function(res) {
            that.getUserInfo(res.data);
          }
        })
      }
    })
  },
  getUserInfo: function(openId) {
    let that = this;
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          wx.getUserInfo({
            success: function(res) {
              let userInfo = res.userInfo;
              userInfo.openId = openId;
              if (handle.is_empty(userInfo) == 1) {
                //首次授权
                that.authorization(userInfo);
              } else {
                //授权过的用户 (更新数据)
                that.authorization(userInfo);
              }
            }
          })
        }
      }
    })
  },
  authorization: function (userInfo) {
    console.log(userInfo);
    wx.request({
      url: data.lyf_host_api_url + '/public/index.php/energy/api.User/wxLogin',
      method: "POST",
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      data: userInfo,
      success: function (res) {
        if(res.data.code == 1){
          res.data.msg = '欢迎访问!';
        }
        wx.showToast({
          title: res.data.msg,
          duration: 1500
        })
      }
    });
  }
})